<script setup lang="ts">
type PropsState = {
  list: any[]
}
const props = withDefaults(defineProps<PropsState>(), {
  list: () => []
})
const $clone = inject('$clone') as <T>(data: T) => T
const emit = defineEmits(['select'])

const scrollContainer = ref<HTMLDivElement | null>(null)
const { arrivedState } = useScroll(scrollContainer)
let isDragging = false
let startX = 0
let scrollLeft = 0

const handScroll = (type: 'left' | 'right') => {
  if (!scrollContainer.value) return
  const scrollAmount = scrollContainer.value.clientWidth
  scrollContainer.value.classList.add('scroll-transition')
  if (type === 'left') {
    scrollContainer.value.scrollLeft -= scrollAmount
  } else if (type === 'right') {
    scrollContainer.value.scrollLeft += scrollAmount
  }
  setTimeout(() => {
    scrollContainer.value?.classList.remove('scroll-transition')
  }, 500) // Match the duration of the CSS transition
}

const onMouseDown = (e: MouseEvent) => {
  isDragging = true
  startX = e.pageX - (scrollContainer.value?.offsetLeft || 0)
  scrollLeft = scrollContainer.value?.scrollLeft || 0
}

const onMouseMove = (e: MouseEvent) => {
  if (!isDragging) return
  e.preventDefault()
  const x = e.pageX - (scrollContainer.value?.offsetLeft || 0)
  const walk = (x - startX) * 2 // scroll-fast
  if (scrollContainer.value) {
    scrollContainer.value.scrollLeft = scrollLeft - walk
  }
}

const handSelect = (item: any, reload = true) => {
  if (!scrollContainer.value) return
  const containerWidth = scrollContainer.value.clientWidth
  const itemElement = scrollContainer.value.querySelector(
    `[data-id="${item.id}"]`
  )
  if (!itemElement) return
  const itemWidth = itemElement.clientWidth
  const itemLeft = itemElement.offsetLeft
  const scrollPosition = itemLeft - containerWidth / 2 + itemWidth / 2
  scrollContainer.value.scrollTo({
    left: scrollPosition,
    behavior: 'smooth'
  })
  if (reload) {
    emit('select', item)
  }
}

const tabChange = (curren: number) => {
  handSelect(tableData.value[curren], false)
}

const onMouseUp = () => {
  isDragging = false
}
let timer: any = null
const showImgChange = (scrollLeft: number) => {
  clearTimeout(timer)
  timer = null
  const index = Math.ceil(scrollLeft / 140) + 1
  const minIndex = index - 8
  const maxIndex = index + 8
  tableData.value.forEach((el, index) => {
    if (index >= minIndex && index <= maxIndex) {
      el.show = true
    }
  })
}
const onScroll = e => {
  if (timer) {
    clearTimeout(timer)
  }
  timer = setTimeout(() => {
    showImgChange(e.target.scrollLeft)
  }, 220)
}

onMounted(() => {
  if (scrollContainer.value) {
    scrollContainer.value.addEventListener('mousedown', onMouseDown)
    scrollContainer.value.addEventListener('mousemove', onMouseMove)
    scrollContainer.value.addEventListener('mouseup', onMouseUp)
    scrollContainer.value.addEventListener('mouseleave', onMouseUp)
    scrollContainer.value.addEventListener('wheel', onWheel)
    scrollContainer.value.addEventListener('scroll', onScroll)
  }
})

onBeforeUnmount(() => {
  if (scrollContainer.value) {
    scrollContainer.value.removeEventListener('mousedown', onMouseDown)
    scrollContainer.value.removeEventListener('mousemove', onMouseMove)
    scrollContainer.value.removeEventListener('mouseup', onMouseUp)
    scrollContainer.value.removeEventListener('mouseleave', onMouseUp)
    scrollContainer.value.removeEventListener('wheel', onWheel)
    scrollContainer.value.removeEventListener('scroll', onScroll)
  }
})

const onWheel = (e: WheelEvent) => {
  if (scrollContainer.value) {
    e.preventDefault()
    scrollContainer.value.scrollLeft += e.deltaY
  }
}

const tableData = ref<any[]>([])
const init = () => {
  tableData.value = $clone(props.list).map((el, index) => {
    el.show = index < 5
    return el
  })
}
defineExpose({
  tabChange,
  init
})
</script>

<template>
  <div class="scroll-w">
    <div class="scroll" ref="scrollContainer">
      <div
        class="card"
        v-for="item in tableData"
        :key="item.id"
        :data-id="item.id"
      >
        <template v-if="item.show">
          <img v-lazy="$getImg(item.image_url, 1)" @click="handSelect(item)" />
        </template>
      </div>
    </div>
    <div class="pre-btn" v-if="!arrivedState.left" @click="handScroll('left')">
      <i class="esayIcon esayIcon-gengduo"></i>
    </div>
    <div
      class="next-btn"
      v-if="!arrivedState.right"
      @click="handScroll('right')"
    >
      <i class="esayIcon esayIcon-gengduo"></i>
    </div>
  </div>
</template>

<style scoped lang="scss">
.scroll-w {
  position: relative;
  .pre-btn,
  .next-btn {
    position: absolute;
    top: calc(50% - 12.5px);
    width: 25px;
    height: 25px;
    border-radius: 50%;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
    background: #ffffff;
    border: 1px solid #f1f2f3;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: transform 0.2s, -webkit-transform 0.2s;
    i {
      font-size: 12px;
      font-weight: bold;
    }
    &:hover {
      transform: scale(1.2);
    }
  }
  .pre-btn {
    left: -10px;
    i {
      transform: rotate(180deg);
    }
  }
  .next-btn {
    right: -10px;
  }
}
.scroll {
  display: flex;
  overflow-x: scroll;
  overflow-y: hidden;
  -webkit-user-select: none; /* Safari */
  -moz-user-select: none; /* Firefox */
  -ms-user-select: none; /* Internet Explorer/Edge */
  user-select: none; /* 标准语法 */
  scrollbar-width: none; /* Firefox */
  gap: 0 10px;
  .card {
    padding: 10px 0;
    min-width: 140px;
    max-width: 140px;
    display: flex;
    align-items: center;
    transition: transform 0.2s;
    border-radius: 5px;
    &:hover {
      transform: scale(1.1);
    }
    img {
      width: 100%;
      aspect-ratio: 12/5;
      cursor: pointer;
      -webkit-user-drag: none;
      display: block;
      border-radius: 5px;
      object-fit: cover;
    }
  }
}

.scroll-transition {
  scroll-behavior: smooth; /* Smooth scrolling */
  transition: scroll-left 0.5s; /* Scroll transition */
}
</style>
<style>
.prive-scroll-loading {
  width: 100%;
  height: 60px;
  object-fit: cover;
  cursor: pointer;
  -webkit-user-drag: none;
  display: block;
  border-radius: 5px;
}
</style>
